#!/usr/bin/python
# coding=utf-8

import urllib
import urlparse
import re
import datetime
from helpers import read_url, decode, split_name

patterns = {
    'name': re.compile('SIZE=5>(?:\s*<[bp]>)?(?:\s*<[bp]>)?(?:\s*<fieldset>)?([^<]+)(?:</fieldset>)?\s*(?:</[bp]>)?\s*(?:</[bp]>)?\s*</FONT>', re.I|re.M|re.U),
    'img': re.compile('<IMG SRC="([^"]+)" BORDER="0"', re.I|re.M),
    'party': re.compile('<A HREF="../kluby/([^"]+).htm">', re.I|re.M),
    'mail': re.compile('e-mail: <A HREF="mailto:([^"]+)">', re.I|re.M),
    'www': re.compile('Strona internetowa: (?:</FONT>)?<A HREF="([^"]+)"', re.I|re.M),
    'sex': re.compile('Urodził(a?) się', re.I|re.M),
}

#<B><FONT FACE="Arial" SIZE=5><P>Zbigniew Romaszewski</p> </B></FONT>

def get_name(soup):
    match = patterns['name'].search(soup)
    if not match:
        print soup
    return match.group(1)

def get_img(soup):
    match = patterns['img'].search(soup)
    return match.group(1)

def get_joindate(soup):
    match = patterns['joindate'].search(soup)
    return datetime.date(int(match.group(3)),
                         int(match.group(2)),
                         int(match.group(1)))

def get_party(soup):
    match = patterns['party'].search(soup)
    if not match:
        return None
    return match.group(1)

def get_mail(soup):
    match = patterns['mail'].search(soup)
    if not match:
        return None
    return match.group(1)

def get_www(soup):
    match = patterns['www'].search(soup)
    if not match:
        return None
    return match.group(1)

def get_sex(soup):
    match = patterns['sex'].search(soup)
    if not match:
        return None
    return 'f' if len(match.group(1)) else 'm'

def get_member(path):
    source = read_url(path)
    member = {
        'name': decode(get_name(source)),
        'img': urlparse.urljoin(path, get_img(source)),
        'party': decode(get_party(source)),
        'email': get_mail(source),
        'www': get_www(source),
        'sex': get_sex(source),
        'path': path,
    }

    return member


def main():
    path = 'http://www.senat.gov.pl/k7/senat/senator/bisztyga.htm'
    member = get_member(path)
    print member
    

if __name__ == "__main__":
    main()
